package com.augrain.microframework.trace.instrument.feign;

import com.augrain.microframework.core.spring.SpringUtils;
import com.augrain.microframework.core.util.IpUtils;
import com.augrain.microframework.core.util.StringUtils;
import com.augrain.microframework.trace.TraceConstant;
import com.augrain.microframework.trace.common.spanid.SpanIdGenerator;
import com.augrain.microframework.trace.context.TraceContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * trace feign 请求拦截器
 *
 * @author biaoy
 * 2021/8/21
 */
public class TraceFeignInterceptor implements RequestInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(TraceFeignInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String traceId = TraceContext.getTraceId();
        if (StringUtils.isNotEmpty(traceId)) {
            requestTemplate.header(TraceConstant.TRACE_ID, traceId);
            requestTemplate.header(TraceConstant.SPAN_ID, SpanIdGenerator.generateNextSpanId());
            requestTemplate.header(TraceConstant.FROM_APP, SpringUtils.getApplicationName());
            requestTemplate.header(TraceConstant.FROM_IP, IpUtils.getLocalIp());
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[TRACE]本地threadLocal变量没有正确传递traceId,本次调用不传递traceId");
            }
        }
    }
}
